using Castle.ActiveRecord;
using Natrue.Data.FastMapping;

namespace Natrue.Data.InitHelper
{
    
    public class SmartListViewInitHelper<T> : System.IDisposable
    {
        private readonly SmartListView listView;
        private int fieldIndex = 1;
        private bool created;

        public SmartListViewInitHelper(string viewName)
            : this(viewName, viewName)
        {

        }

        public SmartListViewInitHelper(string viewName, string viewCaption)
        {
            listView = new SmartListView
                           {
                               BusinessObjectFullname = typeof (T).FullName,
                               ViewName = viewName,
                               ViewCaption = viewCaption
                           };
        }

        public void AddField(string propertyName)
        {
            listView.Items.Add(new SmartListViewItem { OrderIndex = fieldIndex++, PropertyName = propertyName });
        }

        public void AddField(string propertyName, string propertyCaption)
        {
            listView.Items.Add(new SmartListViewItem
                                   {
                                       OrderIndex = fieldIndex++,
                                       PropertyName = propertyName,
                                       Caption = propertyCaption
                                   });
        }

        public void Create()
        {
            created = true;
            foreach (SmartListViewItem item in listView.Items)
                ActiveRecordMediator.Create(item);
            ActiveRecordMediator.Create(listView);
        }

        public void Dispose()
        {
            if (!created) Create();
        }
    }
}